package ua.org.extjsbuilder.wizards;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

public class ExtjsNewProjectWizardPage extends WizardPage {
	private static final String ALLOWED_CHARS_IN_NAME = "[a-zA-Z0-9]+";
	private Text nameText;
	
	public ExtjsNewProjectWizardPage() {
		super("firstPage");
		setTitle("New Extjs Project");
		setDescription("This wizard creates a new Extjs Project.");
	}

	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 3;
		layout.verticalSpacing = 9;
		Label label = new Label(container, SWT.NULL);
		label.setText("&Project Name:");

		nameText = new Text(container, SWT.BORDER | SWT.SINGLE);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		nameText.setLayoutData(gd);
		nameText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});
		setPageComplete(false);
		setControl(container);
	}

	public String getProjectName() {
		return nameText.getText();
	}

	private void dialogChanged() {
		String name = nameText.getText();
		if(name==null||name.trim().length()==0){
			updateStatus("Please, enter the valid name for new project");
			return;	
		}
		if (!name.matches(ALLOWED_CHARS_IN_NAME)) {
			updateStatus("Only alphabetical characters are allowed in the project name");
			return;
		}
		if(isProjectExists(name)){
			updateStatus("The entered project is exists.");
			return;
		}
		updateStatus(null);
	}
	
	private boolean isProjectExists(String name) {
		IProject[] projects = ResourcesPlugin.getWorkspace()
										.getRoot().getProjects();
		for(IProject project : projects){
			if(project.getName().equals(name)){
				return true;
			}
		}
		return false;
	}

	private void updateStatus(String message) {
		setErrorMessage(message);
		setPageComplete(message == null);
	}
}
